package com.lx.chat.biz.impl;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException;
import com.lx.chat.web.WebsocktDo;
import com.lx.chat.web.vo.Msg;
import com.lx.chat.web.vo.WebsocktPropertise;

import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.Session;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class MyMsgSender extends DefaultMsgSender {

    @Autowired
    WebsocktPropertise propertise;

    @Override
    public void send(Msg msg) throws Exception {

        String content =  msg.getContent();
        MsgBody msgBody = null;
        try{
            // 将content解析为MsgBody对象的格式，如果不符合格式将会报JsonParseException
            msgBody = objectMapper.readValue(content, MsgBody.class);

        }catch (JsonParseException | UnrecognizedPropertyException e){
            // 上线 下线的消息 群发
            super.send(msg);
            return;
        }

        // 重新设置内容
        msg.setContent(msgBody.getContent());
        if(!msgBody.getRecvId().equals("")){
            Map<String, Session> onlines = new ConcurrentHashMap<>();
            Session session = WebsocktDo.getOnlines().get(msgBody.getRecvId());
            onlines.put(msgBody.getRecvId(), session);
            Map<String, Object> author = (Map<String, Object>) msg.getAuthor();
            String id = author.get("id") + "";
            System.out.println(id + "=====================================");
            Session session2 = WebsocktDo.getOnlines().get(id);
            onlines.put(id, session2);
            System.out.println(onlines);
            onlines.forEach((ids, sessions)->{
                try {
                    String json = objectMapper.writeValueAsString(msg);
                    sessions.getBasicRemote().sendText(json);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }

            });
        }else {
            super.send(msg);
        }

    }

    @Data
    public static class MsgBody{
        // 消息
        private String content;
        // 接收者id
        private String recvId;
//        // 弹幕颜色
//        private String color;
//        // 视频时间
//        private double videotime;
//        // 发送者id
//        private int id;
    }
}
